package cn.cutie.clotrpc.core.registry.clot;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Description: check health for registry
 * @Author: Cutie
 * @CreateDate: 2024/4/27 19:22
 * @Version: 0.0.1
 */
@Slf4j
public class ClotHealthChecker {
    ScheduledExecutorService consumerExecutor = null;
    ScheduledExecutorService providerExecutor = null;

    public void start() {
        log.info(" ===> [ClotRegistry] start health checker");
        consumerExecutor = Executors.newScheduledThreadPool(1);
        providerExecutor = Executors.newScheduledThreadPool(1);

    }

    public void stop() {
        log.info(" ===> [ClotRegistry] stop health checker");
        gracefulShutdown(consumerExecutor);
        gracefulShutdown(providerExecutor);
    }

    public void consumerChecker(Callback callback){
        consumerExecutor.scheduleWithFixedDelay(() -> {
            try {
                callback.call();
            } catch (Exception e) {
                log.error( "[ClotRegistry] consumer checker error: {}", e);
            }
        }, 1000, 5000, TimeUnit.MILLISECONDS);
    }

    public void providerChecker(Callback callback){
        // 生产者服务保活
        providerExecutor.scheduleAtFixedRate(() -> {
            try {
                callback.call();
            } catch (Exception e){
                log.error("[ClotRegistry] provider checker error: {}", e);
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

    private void gracefulShutdown(ScheduledExecutorService executorService) {
        executorService.shutdown();
        try {
            executorService.awaitTermination(1000, TimeUnit.MILLISECONDS);
            if(!executorService.isTerminated()) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            // ignore
        }
    }

    public interface Callback{
        void call() throws Exception;
    }

}
